package com.wx.springboot.step7.service.impl;

import com.wx.springboot.step7.entity.User;
import com.wx.springboot.step7.repository.UserRepository;
import com.wx.springboot.step7.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void saveUser(int count){
        if (count <= 0) {
            count = 10;
        }
        // 先存n个再说
        for (int i = 1; i <= count; i++) {
            User user = new User();
            user.setUsername("userName_" + i);
            user.setPassword("123456");
            user.setEmail("email_" + i + "@163.com");
            user.setNickName("nickName_" + i);
            user.setRegTime(new Date());
            userRepository.save(user);
        }
    }

    @Override
    public void queryBase(){
        long count = userRepository.count();
        log.info("count ===============>>> {}",count);
        if (count < 3) {
            return;
        }
        List<User> userList = userRepository.findAll();
        log.info("findAll ===============>>> {}",userList.toString());

        Optional<User> findById = userRepository.findById(2L);
        User user = findById.get();
        log.info("findById ===============>>> {}",user.toString());

        User one = userRepository.getOne(2L);
        log.info("getOne ===============>>> {}",one.toString());
    }

    @Override
    public Page<User> queryPage(int page,int size){
        Pageable pageable = PageRequest.of(page,size, Sort.by("id"));
        Page<User> list = userRepository.findAll(pageable);
        log.info("queryPage --> list : {}",list);
        return list;
    }

    @Override
    public void querySql() {
        User email = userRepository.findByEmail("email_6@163.com");
        log.info("findByEmail --> email : {}",email);

        userRepository.deleteById(9L);

        userRepository.modifyById("哈哈哈哈",8L);

        Pageable pageable = PageRequest.of(1,3, Sort.by("id"));
        Page<User> all = userRepository.findALL(pageable);
        log.info("findALL --> all : {}",all.toString());
    }
}
